const connect = require("../models/connect")
const user = require("../models/userDetail")
const message = require("../models/message")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

//返回图片
router.post('/', (req, res, next) => {
  var form = new formidable.IncomingForm();
  form.parse(req, function (err, fields, files) {
    if (err) {
        res.json({ 'state': false })
    } else { 
      let inform = () => {
        return new Promise(function (resolve, reject) {
          user.find({
            userGroup: {
              $in: fields.targetGroup
            }
          }, {
            UUID: 1
          }, (err, docs) => {
            if (err) {
              console.log({ 'state': false, 'msg': error });
            } else {
              let description = "" 
           
              description = "有用户提出新的反馈：" + fields.type
              
              docs.forEach(element => {
                // console.log(element)
                message.create({
                  type: "user_feedback",
                  content: description,
                  UUID: element.UUID,
                  target: "",
                  result: "",
                  status: "unread"
                }, (error, doc) => {
                  if (error) {
                    console.log({ 'state': false, 'msg': error });
                  } else {
                    console.log({ 'state': true, 'msg': "ok" });
                    resolve()
                  }
                })
              });  
            }
          })
        })
      }

      let __connect = () => {
        connect.create({
          authorUUID: fields.authorUUID,
          authorUsername: fields.authorUsername,
          type: fields.type,
          content: fields.content,
          authorRole: fields.authorRole,
          time: fields.time
        }, (error, doc) => {
          if (error) {
            res.json({ 'state': false, 'msg': error });
          } else {
            res.json({ 'state':true, 'msg': doc });
          }
        })
      }

      inform().then(__connect)
    }
  });

});

module.exports = router;